<template>
  <view>
    <view
      style="
        width: 95%;
        margin: 20rpx auto;
        border-radius: 20rpx;
        box-shadow: 0 0 10rpx #eee;
        background: #fff;
      "
    >
      <view class="head flex-col flex-x-center flex-y-center">
        <view style="font-weight: 600">余额（元）</view>
        <view>{{ wallet }}</view>
      </view>
      <view class="yecz">
        <!-- <view>-余额充值-</view> -->
        <view class="hbcells">
          <view
            @tap="tabClick"
            class="hbcell"
            :id="index"
            :style="
              'border:2rpx solid ' +
              (activeIndex == index ? color : '#E1E1E1') +
              ';' +
              'color:' +
              (activeIndex == index ? color : '#000')
            "
            v-for="(item, index) in czhd"
            :key="index"
          >
            <view>{{ item.full }}元</view>

            <view :style="'color:' + (activeIndex == index ? color : '#000')"
              >送{{ item.reduction }}元</view
            >
          </view>
        </view>
        <view class="hbcells">
          <view
            @tap="tabClick1"
            class="hbcell"
            :style="
              'border:2rpx solid ' +
              (activeIndex == -1 ? color : '#E1E1E1') +
              ';padding:0 20rpx;'
            "
          >
            <input
              @input="bindinput"
              maxlength="6"
              placeholder="其他金额"
              placeholderStyle="font-size:24rpx;color:#333;"
              type="digit"
            />
          </view>
        </view>
      </view>
    </view>
    <view class="weui-btn-area">
      <button
        @tap="dayaFormSubmit"
        class="weui-btn"
        :disabled="loading"
        :loading="loading"
        :style="'background:' + color + ';color:#fff;'"
      >
        去充值
      </button>
    </view>
    <view
      @tap="lookck"
      class="read"
      style="display: flex; justify-content: center"
    >
      <!-- <radio
        :checked="true"
        :color="color"
        style="transform: scale(0.8)"
      ></radio> -->
      <view>
        点击充值即代表同意
        <text class="readfont" :style="'color:' + color">《充值服务协议》</text>
      </view>
    </view>


    <daya-pay
        v-if="show_pay_box"
        :type="2"
        :order_id="pay_order_id"
        :mp_openid="wx_openid"
        :show_pay_box="show_pay_box"
        :kqyue="kqyue"
        jf_proportion=""
        :totalPrice="totalMoney"
        :user_wallet="userInfo.wallet"
        :hdfk="false"
        @close_pay_box="show_pay_box=false"
        @pay_success="pay_success"
        @pay_error="pay_error"
    ></daya-pay>

  </view>
</template>

<script>
import cardlist from '@/ymq_canyino2o/dist/cardlist/index'
import gettel from '@/ymq_canyino2o/dist/gettel/index'
import util from "@/ymq_canyino2o/utils/util";
var app = getApp()
export default {
  components: {
    cardlist,
    gettel
  },
  data() {
    return {
      totalMoney: 0,//充值金额
      pay_order_id: 0,//跑腿订单id
      show_pay_box: false,
      kqyue:false,
      wx_openid: '',
      userInfo: {
        wallet: '0'
      },
      //====================================

      czhd: [],
      activeIndex: 0,
      czmoney: 0,
      loading: false,
      wallet: '',
      userinfo: '',
      color: ''
    }
  },
  mounted() {
    this.load_pay_box_data();
  },
  onLoad: function (e) {
    app.globalData.setNavigationBarColor(this)
    var that = this
    var a = uni.getStorageSync('users').id
    app.globalData.util.request({
      url: 'entry/wxapp/UserInfo',
      cachetime: '0',
      data: {
        user_id: a
      },
      success: function (e) {
        console.log(e)
        that.setData({
          wallet: e.data.wallet,
          userinfo: e.data
        })
      }
    })
    app.globalData.util.request({
      url: 'entry/wxapp/Czhd',
      cachetime: '0',
      success: function (e) {
        console.log(e)
        if (0 < e.data.length) {
          that.setData({
            czhd: e.data,
            czmoney: e.data[0].full
          })
          that.totalMoney=that.czmoney
        }
      }
    })
  },
  onReady: function () {},
  onShow: function () {},
  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () {},
  onReachBottom: function () {},
  methods: {
    dayaFormSubmit () {
      app.globalData.util.requestSM('recharge').then( (e)=>{

        if (Number(this.czmoney) <= 0) {
          uni.showModal({
            title: '提示',
            content: '充值金额不能小于0'
          })
          return
        }

        //todo 原来这里逻辑有问题,服务器端限制下吧

        console.log("计算满减1", Number(this.czmoney))
        console.log("计算满减2", Number(this.czhd[this.czhd.length - 1].full))
        var _cz_money = 0
        var _mj = this.jsmj(this.czmoney, this.czhd)
        if (0 == this.czhd.length) {
          _cz_money = this.czmoney
        } else if (_mj>=0) {
          //计算满减
          console.log("计算满减3", _mj)
          _cz_money = Number(this.czmoney) + Number(this.czhd[_mj].reduction)
        } else {
          _cz_money = this.czmoney
        }
        this.loading=true

        uni.showLoading({
          title: '加载中',
          mask: true
        })
        app.globalData.util.request({
          url: 'entry/wxapp/AddCzorder',
          cachetime: '0',
          data: {
            user_id: this.userinfo.id,
            money: this.czmoney,
            money2: _cz_money - this.czmoney
          },
          success:  (res)=>{
            console.log("充值订单",res.data)
            this.loading=false
            this.pay_order_id=res.data
            this.show_pay_box=true
          }
        })

      })

    },
    pay_success() {
      this.show95Modal("充值成功,预计5秒内到账", "成功", "知道啦", () => {
        //刷新本页面余额数据
        // this.onLoad()
      });
    },
    pay_error() {
      this.show95Modal("支付失败了", "支付失败", "知道啦", () => {

      });
    },
    load_pay_box_data() {
      this.kqyue=false
      // this.kqyue=getApp().globalData.xtxx.is_yuepay=='1'

      var h = uni.getStorageSync('users').id
      app.globalData.util.request({
        url: 'entry/wxapp/UserInfo',
        cachetime: '0',
        data: {
          user_id: h
        },
        success: (t)=> {
          var a = util.formatTime(new Date()).substring(0, 10).replace(/\//g, '-')
          if ('' != t.data.dq_time && t.data.dq_time >= a.toString()) {
            t.data.ishy = 1
          }
          this.userInfo=t.data
        }
      })

    },
    //************************************
    lookck: function () {
      uni.navigateTo({
        url: '../car/xydtl?title=充值服务协议'
      })
    },

    tabClick: function (e) {
      this.setData({
        activeIndex: e.currentTarget.id,
        czmoney: Number(this.czhd[e.currentTarget.id].full)
      })
      this.totalMoney=this.czmoney
    },

    tabClick1: function (e) {
      this.setData({
        activeIndex: -1,
        czmoney: 0
      })
    },

    bindinput: function (e) {
      var t
      console.log(e.detail.value)
      if ('' != e.detail.value) {
        t = e.detail.value
      } else {
        t = 0
      }
      this.setData({
        czmoney: parseFloat(t)
      })
      this.totalMoney=this.czmoney
    },

    //计算满减
    jsmj: function (e, t) {
      var a = -1 ;
      var n = 0;
      for (n=0; n < t.length; n++) {
        if (Number(e) >= Number(t[n].full)) {
          a = n
          break
        }
      }
      return a
    },

    tjddformSubmit: function (s) {
      var that = this
      app.globalData.util.requestSM('recharge').then(function (e) {
        var a = that
        var n = (s.detail.formId, that.userinfo.openid)
        var o = that.czmoney
        var t = that.czhd
        var i = that.userinfo.id
        console.log(t)
        if (Number(o) <= 0) {
          uni.showModal({
            title: '提示',
            content: '充值金额不能小于0'
          })
        } else {
          if (0 == t.length) var c = o
          else if (Number(o) >= Number(that.czhd[t.length - 1].full)) {
            var l = that.jsmj(o, t)
            console.log(l)
            c = Number(o) + Number(t[l].reduction)
          } else {
            c = o
          }
          that.setData({
            loading: true
          })
          uni.showLoading({
            title: '加载中',
            mask: true
          })
          app.globalData.util.request({
            url: 'entry/wxapp/AddCzorder',
            cachetime: '0',
            data: {
              user_id: i,
              money: o,
              money2: c - o
            },
            success: function (e) {
              console.log(e)
              var t = e.data
              app.globalData.util.request({
                url: 'entry/wxapp/pay',
                cachetime: '0',
                data: {
                  openid: n,
                  money: o,
                  order_id: t,
                  type: 2
                },
                success: function (e) {
                  console.log(e)
                  uni.requestPayment({
                    timeStamp: e.data.timeStamp,
                    nonceStr: e.data.nonceStr,
                    package: e.data.package,
                    signType: e.data.signType,
                    paySign: e.data.paySign,
                    success: function (e) {
                      console.log(e)
                    },
                    complete: function (e) {
                      console.log(e)
                      if ('requestPayment:fail cancel' == e.errMsg) {
                        uni.showToast({
                          title: '取消支付'
                        })
                        a.setData({
                          loading: false
                        })
                      }
                      if ('requestPayment:ok' == e.errMsg) {
                        uni.showModal({
                          title: '提示',
                          content: '支付成功',
                          showCancel: false
                        })
                        setTimeout(function () {
                          uni.navigateBack({})
                        }, 1000)
                      }
                    }
                  })
                }
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style>
@import './walletadd.css';
</style>
